package pers.lance.firstweb.servlet;

import pers.lance.firstweb.bean.User;
import pers.lance.firstweb.dao.UserManager;
import pers.lance.firstweb.dao.UserManagerImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * add user servlet
 *  url /adduser
 */
@WebServlet(name = "AddUserServlet", urlPatterns = "/adduser")
public class AddUserServlet extends UserInterceptServlet {
    UserManager userManager = new UserManagerImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        User userCache = (User) session.getAttribute("usercache");
        User user = null;
        if (userCache != null) {
            user = userCache;
            session.setAttribute("usercache", null);
        } else {
            user = createUserFromReq(request);
        }
        userManager.addUser(user);
        request.getRequestDispatcher("/findall").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
